const { pool } = require('../config/database');
const { formatDateTime } = require('../utils/dateFormatter');
const logger = require('../utils/logger');

class RoleModel {
  // 创建角色
  async create(roleData) {
    try {
      const [result] = await pool.execute(
        `INSERT INTO roles (name, code, description, status) 
         VALUES (?, ?, ?, ?)`,
        [
          roleData.name,
          roleData.code,
          roleData.description || null,
          roleData.status !== undefined ? roleData.status : 1
        ]
      );
      return result.insertId;
    } catch (error) {
      logger.error('创建角色失败:', error);
      throw error;
    }
  }

  // 通过ID获取角色
  async findById(id) {
    try {
      const [rows] = await pool.execute(
        `SELECT id, name, code, description, status, created_at, updated_at 
         FROM roles 
         WHERE id = ? AND is_deleted = 0`,
        [id]
      );
      return rows[0] ? this.formatRoleData(rows[0]) : null;
    } catch (error) {
      logger.error('查询角色失败:', error);
      throw error;
    }
  }

  // 获取所有角色
  async findAll(params = {}) {
    try {
      let query = `
        SELECT id, name, code, description, status, created_at, updated_at 
        FROM roles 
        WHERE is_deleted = 0
      `;
      
      const queryParams = [];
      
      // 添加查询条件
      if (params.name) {
        query += ` AND name LIKE ?`;
        queryParams.push(`%${params.name}%`);
      }
      
      if (params.status !== undefined) {
        query += ` AND status = ?`;
        queryParams.push(params.status);
      }
      
      // 添加排序
      query += ` ORDER BY id ASC`;
      
      // 添加分页
      if (params.page && params.size) {
        const offset = (params.page - 1) * params.size;
        query += ` LIMIT ?, ?`;
        queryParams.push(offset, parseInt(params.size));
      }
      
      // 执行查询
      const [rows] = await pool.execute(query, queryParams);
      
      // 获取总数
      let countQuery = `
        SELECT COUNT(*) as total 
        FROM roles 
        WHERE is_deleted = 0
      `;
      
      const countParams = [];
      
      if (params.name) {
        countQuery += ` AND name LIKE ?`;
        countParams.push(`%${params.name}%`);
      }
      
      if (params.status !== undefined) {
        countQuery += ` AND status = ?`;
        countParams.push(params.status);
      }
      
      const [countResult] = await pool.execute(countQuery, countParams);
      const total = countResult[0].total;
      
      return {
        list: rows.map(row => this.formatRoleData(row)),
        total
      };
    } catch (error) {
      logger.error('查询所有角色失败:', error);
      throw error;
    }
  }

  // 更新角色
  async update(id, roleData) {
    try {
      const updateFields = [];
      const params = [];
      
      // 动态构建更新字段
      if (roleData.name !== undefined) {
        updateFields.push('name = ?');
        params.push(roleData.name);
      }
      
      if (roleData.description !== undefined) {
        updateFields.push('description = ?');
        params.push(roleData.description);
      }
      
      if (roleData.status !== undefined) {
        updateFields.push('status = ?');
        params.push(roleData.status);
      }
      
      // 如果没有要更新的字段，直接返回
      if (updateFields.length === 0) {
        return false;
      }
      
      // 添加ID参数
      params.push(id);
      
      const [result] = await pool.execute(
        `UPDATE roles SET ${updateFields.join(', ')} WHERE id = ? AND is_deleted = 0`,
        params
      );
      
      return result.affectedRows > 0;
    } catch (error) {
      logger.error('更新角色失败:', error);
      throw error;
    }
  }

  // 软删除角色
  async softDelete(id) {
    try {
      // 检查是否有用户关联此角色
      const [userRows] = await pool.execute(
        'SELECT COUNT(*) as count FROM users WHERE role_id = ? AND is_deleted = 0',
        [id]
      );
      
      if (userRows[0].count > 0) {
        throw new Error('该角色下存在关联用户，无法删除');
      }
      
      // 开启事务
      const connection = await pool.getConnection();
      await connection.beginTransaction();
      
      try {
        // 删除角色菜单关联
        await connection.execute(
          'DELETE FROM role_menus WHERE role_id = ?',
          [id]
        );
        
        // 软删除角色
        const [result] = await connection.execute(
          'UPDATE roles SET is_deleted = 1 WHERE id = ?',
          [id]
        );
        
        // 提交事务
        await connection.commit();
        
        return result.affectedRows > 0;
      } catch (error) {
        // 回滚事务
        await connection.rollback();
        throw error;
      } finally {
        // 释放连接
        connection.release();
      }
    } catch (error) {
      logger.error('删除角色失败:', error);
      throw error;
    }
  }

  // 检查角色名称是否存在
  async isNameExists(name, excludeId = null) {
    try {
      let query = 'SELECT 1 FROM roles WHERE name = ? AND is_deleted = 0';
      const params = [name];
      
      if (excludeId) {
        query += ' AND id != ?';
        params.push(excludeId);
      }
      
      const [rows] = await pool.execute(query, params);
      return rows.length > 0;
    } catch (error) {
      logger.error('检查角色名称是否存在失败:', error);
      throw error;
    }
  }

  // 检查角色编码是否存在
  async isCodeExists(code, excludeId = null) {
    try {
      let query = 'SELECT 1 FROM roles WHERE code = ? AND is_deleted = 0';
      const params = [code];
      
      if (excludeId) {
        query += ' AND id != ?';
        params.push(excludeId);
      }
      
      const [rows] = await pool.execute(query, params);
      return rows.length > 0;
    } catch (error) {
      logger.error('检查角色编码是否存在失败:', error);
      throw error;
    }
  }

  // 获取角色菜单
  async getRoleMenus(roleId) {
    try {
      // 检查角色是否存在
      const role = await this.findById(roleId);
      if (!role) {
        return null;
      }
      
      // 获取角色菜单ID列表
      const [rows] = await pool.execute(
        `SELECT menu_id 
         FROM role_menus 
         WHERE role_id = ?`,
        [roleId]
      );
      
      return {
        roleId: Number(roleId),
        menuIds: rows.map(row => row.menu_id)
      };
    } catch (error) {
      logger.error('获取角色菜单失败:', error);
      throw error;
    }
  }

  // 格式化角色数据
  formatRoleData(role) {
    return {
      id: role.id,
      name: role.name,
      code: role.code,
      description: role.description,
      status: role.status,
      created_at: role.created_at ? formatDateTime(role.created_at) : null,
      updated_at: role.updated_at ? formatDateTime(role.updated_at) : null
    };
  }
}

module.exports = new RoleModel(); 